package com.yunshang.ysmall.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.activation.FileTypeMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.nio.entity.NByteArrayEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;


public class HttpClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    // 请求器的配置
    private static RequestConfig requestConfig;

    // 连接超时时间，默认10秒
    private int socketTimeout = 10000;

    // 传输超时时间，默认30秒
    private int connectTimeout = 20000;

    public HttpClientUtils() {
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout)
                .build();
    }

    public static String httpPost(String url, Map<String, String> params) throws Exception {
        HttpClient client = SingletonClient.getHttpClient();
        HttpPost httpost = new HttpPost(url);
        // logger.info("[send to ch]:" + params.toString());
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        }
        requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(20000)
                .build();
        httpost.setConfig(requestConfig);
        try {
            HttpResponse response = client.execute(httpost);
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                // 判断响应实体是否为空
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    // logger.info("[rcv from ch]:" + result);
                    return result;
                    // return EntityUtils.toString(entity);
                }
            } else {
                httpost.abort();
                throw new ClientProtocolException("Unexpected response status: " + status);
            }

        } catch (Exception e) {
            httpost.abort();
            throw new Exception(e);
        }
        return "";
    }

    public static String httpPost(String url, String context, String strFormat, String charset) throws Exception {
        HttpClient client = SingletonClient.getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        // logger.info("[send to ch]:" + context);
        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(context, charset);
        if ("XML".equals(strFormat)) {
            httpPost.addHeader("Content-Type", "text/xml");
        } else {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
        }
        httpPost.setEntity(postEntity);
        httpPost.setConfig(requestConfig);
        try {
            HttpResponse response = client.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                // 判断响应实体是否为空
                if (entity != null) {
                    String result = EntityUtils.toString(entity, charset);
                    // logger.info("[rcv from ch]:" + result);
                    return result;
                }
            } else {
                httpPost.abort();
                throw new ClientProtocolException("Unexpected response status: " + status);
            }

        } catch (Exception e) {
            httpPost.abort();
            throw new Exception(e);
        }
        return "";
    }
    

    public static String httpGet(String url) throws Exception {
        HttpClient client = SingletonClient.getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            // 判断响应实体是否为空
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
        return "";
    }

    private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    
	private static  String generateBoundary() {
        final StringBuilder buffer = new StringBuilder();
        final Random rand = new Random();
        final int count = rand.nextInt(11) + 30; // a random size from 30 to 40
        for (int i = 0; i < count; i++) {
            buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }
        return buffer.toString();
    }
	
    public static void main(String[] args) {
         String url = "http://211.219.83.86:8090/scapi.aspx?client_id=YUNSHANG&schema_name=GET_USER_ACCOUNT_PAY&parameter=";
         String result;
         try {
			String param = URLEncoder.encode("{\"USER_ALIAS\":\"AN809702\",\"PAY_TYPE\":\"3\",\"MONEY\":\"0.1\",\"ORDER_NO\":\"ST12345678\",\"PAY_IP\":\"127.0.0.1\"}","utf-8");
			url = url + param +"&md5=d92417093209b948f6231197f01db4a1&ndate=155345";
			System.out.println(url);
			result = "{\"result\":\"success\",\"total\":1,\"data\":[{\"ISPAY\":\"1|170713100001\"}]}";
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("success".equals(jsonObject.getString("result"))){
				JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
				System.out.println(data.getString("ISPAY").split("|")[0]);
			}
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
//			result = HttpClientUtils.httpGet(url);
//			System.out.println(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         
    }

}
